<?php

namespace app\admin\controller;

use think\Db;
use think\Validate;
use think\Request;
use think\Session;
use app\admin\controller\Base;
use app\admin\controller\Index;

class User extends Base
{
    public function index()
    {
        //SELECT
        //     u.id AS uid,
        //     u. NAME AS uname,
        //     u.username,
        //     r.id AS rid,
        //     r. NAME AS rname
        // FROM
        //     zzz_user AS u
        // LEFT JOIN zzz_user_role AS ur ON u.id = ur.uid
        // LEFT JOIN zzz_role AS r ON ur.rid = r.id;

        
        $ulist = Db::name('user u')
            ->join('user_role ur','u.id = ur.uid','LEFT')
            ->join('role r','ur.rid = r.id','LEFT')
            ->field('u.id as uid,u.name as uname,u.username,r.id as rid,r.name as rname')
            ->order('uid','ASC')
            ->select();
        // dump($ulist);die;
        $res = [];
        foreach($ulist as $k=>$v){
            if(isset($res[$v['uid']])){
                $res[$v['uid']]['rname'] .= ' '.$v['rname'];
            }else{
                $res[$v['uid']] = [
                    'id' => $v['uid'],
                    'name' => $v['uname'],
                    'username' => $v['username'],
                    'rname' => $v['rname']
                ];
            }
        }

       return view('/user/index', [
            'title' => '用户列表',
            'ulist' => $res
        ]);
        
    }

    

    public function add()
    {
        return view('/user/add',[
            'title'=>'用户管理',
            'content'=>'添加用户'
            ]);
    }

    public function doadd()
    {
        $data = input('post.');
        // dump($data);die;
        $rule =['name'  => 'require|regex:/^[_0-9a-zA-Z]{6,16}$/',
                'username'   => 'require|regex:/^[\x{4e00}-\x{9fa5}]{2,16}$/u',
                'userpass' => 'require|regex:/^[_0-9a-zA-Z]{6,16}$/',
                'repass'=>'require|confirm:userpass'
                ];

        $message  =[
            'name.require' => '账号必须填',
            'name.regex'     => '账号6-16位数字字母或者下划线',
            'username.require'   => '真实姓名必须填',
            'username.regex'=>'真实姓名为2-16位中文',
            'userpass.require'  => '密码必须填',
            'userpass.regex'=>'密码6-16位数字字母或者下划线',
            'repass.require'  => '确认密码必须填',
            'repass.confirm' =>'密码不一致'
            ];

        $validate = new Validate($rule,$message);
        $result   = $validate->check($data);
        if(!$result){
            $this->error($validate->getError());
        }else{

            unset($data['repass']);
            $data['userpass'] = sha1($data['userpass']);

            $res =  db('user')->insertGetId($data);
        }
        if($res){
            $this->success('新增成功', '/admin/User');
        }else{
            $this->error('新增失败','/admin/Uadd');
        }
    }


    public function rolelist($id='',$name='')
    {   
        // var_dump($id,$name);die;
        $rolelist = Db::name('role')
            ->field(['id', 'name','remark'])
            ->order('id', 'ASC')
            ->select();
        $role = Db::name('user_role')
            ->field('rid')
            ->where('uid='.$id)
            ->select();
        $arr = [];
        foreach($role as $k => $v){
            $arr[] =  $v['rid'];
        }
        // dump($arr);die;
        return view('user/rolelist',[
            'title'=>'给'.$name.'分配角色',
            'content'=>'角色列表',
            'rolelist'=>$rolelist,
            'arr'=>$arr,
            'uid'=>$id
            ]);
    }

    public function dorole()
    {
        $uid = input('post.uid');
        $data = input('post.juese/a');
        if(!empty($data)){
            foreach($data as $k => $v) {
                $datas[] = [
                    'rid'=>$v,
                    'uid'=>$uid,
                ]; 
            }
        }else{
            $datas = [];
        }
        
        
            Db::startTrans();
            try{
                Db::name('user_role')->where('uid',$uid)->delete();
                $result   =  db('user_role')->insertAll($datas);
                Db::commit();
                // $lastnode = action('Index/selectNode', ['id' => session('admin.id')], 'controller');
                // $lastnode = $this->selectNode(session('admin.id'));
                // $sess = Session::set('admin.node',$lastnode,'think');
                $this->success('角色更新成功', '/admin/User');
            } catch (Exception $e) { 
                Db::rollback();
                $this->error('角色更新失败','/admin/User');
            }  

    }


    public function delete($id='')
    {
        Db::startTrans();
        try{
            Db::name('user_role')->where('uid',$id)->delete();
            Db::name('user')->where('id',$id)->delete();
            
            Db::commit();
            return 200;
        } catch (Exception $e) { 
            Db::rollback();
            return false;
        }  
    }

    public function update($id='')
    {
        $user = Db::name('user')->where('id',$id)->select();
        return view('View/update',[
            'title'=>'编辑'.$user['name'],
            'user'=>$user
            ]);
        
    }

    public function doupdate($id='')
    {
        $data = input('post.');
        $res = Db::name('user')->where('id',$id)->update($data);
        if($res){
            $this->success('编辑成功',"url('admin/User/update','id='.$id)");
        }else{
            $this->error('编辑失败',"url('admin/User/update','id='.$id)");
        }
    }


   

}